package org.i1510.common.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.i1510.common.bean.PageBean;
import org.i1510.common.dao.ISysPopDao;
import org.i1510.common.po.SysAtt;
import org.i1510.common.po.SysPop;
import org.i1510.common.service.ISysPopService;
import org.i1510.common.utils.KBProperties;
import org.i1510.common.utils.PrintWriterUtils;
import org.i1510.common.utils.StringUtils;
import org.i1510.common.utils.file.AuthBeanUtils;
import org.i1510.common.utils.web.ResultMapper;
import org.i1510.common.utils.web.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value = "/admin/sysPop")
public class SysPopController extends BaseAttController {
	private static final Logger logger = LoggerFactory
			.getLogger(SysPopController.class);
	@Autowired
	private ISysPopService iSysPopService;
	@Autowired
	private ISysPopDao iSysPopDao;

	private ResultMapper mapper;

	@RequestMapping(value = "/findMenu", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String findMenu(HttpServletRequest request,
			HttpServletResponse response,
			@Valid @ModelAttribute("sysPop") SysPop sysPop, BindingResult errors) {
		Map conditions = new HashMap();
		List list = iSysPopService.getAll(sysPop, conditions);
		JSONArray jsonArray = new JSONArray();
		if (list.size() > 0) {
			jsonArray = JSONArray.fromObject(list);
		}
		PrintWriterUtils write = new PrintWriterUtils();
		write.sendPrintWriterUtils(response, jsonArray.toString(), "json");
		return null;

	}
	/**
	 * 
	 * @Author Rambo
	 * 
	 * @Desc：获取树结构
	 * 
	 * @param sysPop
	 * 
	 * @param errors
	 * 
	 * @return TODO
	 * 
	 * @Version SysPopController.java,v 1.1 2013-11-15 下午4:20:56
	 */

	@RequestMapping(value = "/findTree", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String findTree(HttpServletRequest request,
			HttpServletResponse response,
			@Valid @ModelAttribute("sysPop") SysPop sysPop, BindingResult errors) {

		Map conditions = new HashMap();

		List list = iSysPopService.getAll(sysPop, conditions);

		JSONArray jsonArray = new JSONArray();

		if (list.size() > 0) {

			jsonArray = JSONArray.fromObject(list);

		}

		PrintWriterUtils write = new PrintWriterUtils();

		write.sendPrintWriterUtils(response, jsonArray.toString(), "json");

		return null;

	}

	@RequestMapping(value = "/listExt", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String listExt(@Valid @ModelAttribute("start") String start,
			@Valid @ModelAttribute("limit") String limit,
			@Valid @ModelAttribute("sysPop") SysPop sysPop,
			@Valid @ModelAttribute("pageBean") PageBean pageBean,
			BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapperRtn = WebUtils.getMapper4Errors(errors);
		} else {
			Map conditions = new HashMap();
			if (!"".equals(start) && !"".equals(limit)) {
				pageBean.setIntPageIndex(StringUtils.String2Integer(start) != 0 ? (StringUtils
						.String2Integer(start)) : 0);
				pageBean.setIntPageSize(StringUtils.String2Integer(limit) != 0 ? (StringUtils
						.String2Integer(limit)) : 0);
			} else {
				pageBean.setIntPageIndex(0);
				pageBean.setIntPageSize(KBProperties.PAGESIZE);
			}
			List list = iSysPopService.getPage(sysPop, pageBean, conditions);
			int totalCount = iSysPopService.getPageCount(sysPop, conditions);
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("total", totalCount);
			mapperRtn.appendResult("root", list);
		}
		return mapperRtn.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：保存对象
	 * @param sysPop
	 * @param errors
	 * @return TODO
	 * @Version SysPopController.java,v 1.1 2013-11-15 下午4:20:56
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public String save(HttpServletRequest request,
			@Valid @ModelAttribute("sysPop") SysPop sysPop, BindingResult errors) {
		ResultMapper mapper = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapper = WebUtils.getMapper4Errors(errors);
		} else {
			// 判断parentId 是否有效
			if (null != sysPop
					&& !StringUtils.isStringEmpty(sysPop.getParentId())) {
				// 通过parentId 判断上级是否存在
				SysPop exist = iSysPopService.findById(sysPop.getParentId());
				if (null != exist) {
					sysPop.setParentId(exist.getDocId());
					sysPop.setParentName(exist.getDocSubject());
				} else {
					sysPop.setParentId("0000");// 默认跟节点
					sysPop.setParentName("所有组织");
				}

			}
			sysPop.setDocStatus("10");
			mapper = iSysPopService.save(sysPop, request);
		}

		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：删除对象
	 * @param docId
	 * @param errors
	 * @return TODO
	 * @Version SysPopController.java,v 1.1 2014-9-2 下午3:38:17
	 */
	@RequestMapping(value = "/deleteX", method = RequestMethod.POST)
	@ResponseBody
	public String deleteX(@Valid @ModelAttribute("docId") String docId,
			BindingResult errors) {

		if (errors.hasErrors()) {
			mapper = WebUtils.getMapper4Errors(errors);
		} else {
			mapper = iSysPopService.delete(docId);
		}

		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：查看对象
	 * @param docId
	 * @param errors
	 * @return TODO
	 * @Version SysPopController.java,v 1.1 2014-9-2 下午3:39:35
	 */
	@RequestMapping(value = "/view", method = RequestMethod.GET)
	@ResponseBody
	public String view(@Valid @ModelAttribute("docId") String docId,
			BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapperRtn = WebUtils.getMapper4Errors(errors);
		} else {
			SysPop sysPop = iSysPopService.findById(docId);
			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", sysPop);
		}
		return mapperRtn.toJson();
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public String list(@ModelAttribute("fromDate") String fromDate,
			@ModelAttribute("toDate") String toDate,
			@Valid @ModelAttribute("sysPop") SysPop sysPop,
			@Valid @ModelAttribute("pageBean") PageBean pageBean,
			BindingResult errors) {
		ResultMapper mapperRtn = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapperRtn = WebUtils.getMapper4Errors(errors);
		} else {
			Map conditions = new HashMap();
			conditions.put("fromDate", fromDate);
			conditions.put("toDate", toDate);
			List sysPops = iSysPopService.getPage(sysPop, pageBean, conditions);
			int totalCount = iSysPopService.getPageCount(sysPop, conditions);
			Map map = new HashMap();
			map.put("pageNo", pageBean.getPageNo());
			map.put("pageSize", pageBean.getPageSize());
			map.put("totalCount", totalCount);
			map.put("listData", sysPops);

			mapperRtn = ResultMapper.generateSuccess();
			mapperRtn.appendResult("data", map);
		}
		return mapperRtn.toJson();
	}

	@RequestMapping(value = "/reloadAuthAccess", method = RequestMethod.POST)
	@ResponseBody
	public String reloadAuthAccess(HttpServletRequest request,
			@ModelAttribute("loaction") String loaction, BindingResult errors) {

		if (errors.hasErrors()) {
			mapper = WebUtils.getMapper4Errors(errors);
			mapper.appendResult("message", "操作失败!");
		} else {
			List<SysPop> list = new ArrayList<SysPop>();
			list = AuthBeanUtils.readAuth4Request(loaction, request);
			mapper = iSysPopService.saveAll(list);
			mapper.appendResult("message", "操作成功!");
		}

		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：状态修改
	 * @param request
	 * @param docId
	 * @param docStatus
	 * @param errors
	 * @return TODO
	 * @Version CateController.java,v 1.1 2014-9-11 上午10:06:04
	 */
	@RequestMapping(value = "/updateStatus00", method = RequestMethod.POST)
	@ResponseBody
	public String updateStatus00(HttpServletRequest request,
			@Valid @ModelAttribute("docId") String docId,
			@Valid @ModelAttribute("docStatus") String docStatus,
			BindingResult errors) {
		mapper = ResultMapper.generateFailure();
		if (errors.hasErrors()) {
			mapper = WebUtils.getMapper4Errors(errors);
		} else {
			if (!StringUtils.isStringEmpty(docId)) {
				// 判断下级是否存在，如果存在不允许删除
				Map conditions = new HashMap();
				conditions.put("parentId", docId);
				if (iSysPopService.getPageCount(null, conditions) > 0) {
					mapper = ResultMapper.generateFailure();
					mapper.appendResult("messages", "下级有关联信息，不能删除!");
				} else {
					SysPop sysPop = new SysPop();

					sysPop.setDocId(docId);
					sysPop.setDocStatus("00");
					mapper = iSysPopService.save(sysPop, request);
				}
			} else {

				mapper.appendResult("messages", "无法找到该ID!");
			}
		}

		return mapper.toJson();
	}

	/**
	 * @Author Rambo
	 * @Desc：状态修改
	 * @param request
	 * @param docId
	 * @param docStatus
	 * @param errors
	 * @return TODO
	 * @Version CateController.java,v 1.1 2014-9-11 上午10:06:04
	 */
	@RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
	@ResponseBody
	public String updateStatus(HttpServletRequest request,
			@Valid @ModelAttribute("docId") String docId,
			@Valid @ModelAttribute("docStatus") String docStatus,
			BindingResult errors) {

		if (errors.hasErrors()) {
			mapper = WebUtils.getMapper4Errors(errors);
		} else {
			if (!StringUtils.isStringEmpty(docId)) {
				SysPop sysPop = new SysPop();

				sysPop.setDocId(docId);
				sysPop.setDocStatus(docStatus);
				mapper = iSysPopService.save(sysPop, request);
			} else {
				mapper = ResultMapper.generateFailure();
				mapper.appendResult("messages", "无法找到该ID!");
			}

		}

		return mapper.toJson();
	}

	@RequestMapping(value = "/uploadExt", method = RequestMethod.POST)
	@ResponseBody
	public String uploadExt(
			@RequestParam(value = "file", required = false) MultipartFile file,
			HttpServletRequest request,HttpServletResponse response, ModelMap model,
			@Valid @ModelAttribute("sysAtt") SysAtt sysAtt, BindingResult errors) {
		// 执行SysAtt通用附件保存
		ResultMapper mapper = upload(file, request, sysAtt);
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		File exsitFile = null;
		// 文件存在
		exsitFile = new File(mapper.getMap().get("path").toString());
		long startTime = System.currentTimeMillis();
		if (mapper.getMap().get("code").equals("1")) {
			try {
				InputStream input = null;
				Workbook workBook = null;
				Sheet sheet = null;

				input = new FileInputStream(exsitFile);

				if (!input.markSupported()) {
					input = new PushbackInputStream(input, 8);
				}
				try {
					if (POIFSFileSystem.hasPOIFSHeader(input)
							|| POIXMLDocument.hasOOXMLHeader(input)) {
						workBook = WorkbookFactory.create(input);
					} else {
						System.out.println("非法的输入流：当前输入流非OLE2流或OOXML流！");
					}
				} catch (IOException e) {
					System.out.println("创建表格工作簿对象发生IO异常！原因：" + e.getMessage());
					e.printStackTrace();
				} catch (InvalidFormatException e) {
					// Your InputStream was neither an OLE2 stream, nor an OOXML
					// stream.
					System.out.println("非法的输入流：当前输入流非OLE2流或OOXML流！");
					e.printStackTrace();
				}
				try {
					if (workBook != null) {
						int numberSheet = workBook.getNumberOfSheets();
						if (numberSheet > 0) {
							sheet = workBook.getSheetAt(0);// 获取第一个工作簿(Sheet)的内容【注意根据实际需要进行修改】
							list = readExcelInfo(sheet);
							//执行插入POP
							mapper = iSysPopService.saveList(list, request);
						} else {
							System.out.println("目标表格工作簿(Sheet)数目为0！");
						}
					}
					input.close();
				} catch (IOException e) {
					System.out.println("关闭输入流异常！" + e.getMessage());
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				System.out.println("未找到指定的文件！");
				e.printStackTrace();
			} catch (Exception e) {
				System.out.println("读取Excel文件发生异常！");
				e.printStackTrace();
			}

		}
		long endTime = System.currentTimeMillis();
		logger.info("解析完毕！共用时" + (endTime - startTime) + "毫秒！");
		PrintWriterUtils write = new PrintWriterUtils();
		write.sendPrintWriterUtils(response, mapper.toJson(), null);
		return null;
	}

	private List<Map<String, String>> readExcelInfo(Sheet sheet) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		int rowCount = sheet.getPhysicalNumberOfRows();// 总行数
		if (rowCount > 1) {
			Row titleRow = sheet.getRow(0);//带有字段名的记录标题行
			for (int i = 2; i < rowCount; i++) {// 遍历行，略过标题行，从第三行开始
				Map<String, String> map = new HashMap<String, String>();
				Row row = sheet.getRow(i);
				for (int j = 0; j < 13; j++) {// j为需要度取的列，跳过第一列
					Cell cell = row.getCell(j);
					
					if (cell != null && cell.getCellType() == cell.CELL_TYPE_STRING) {
						map.put(titleRow.getCell(j).getStringCellValue(), cell.getStringCellValue().trim());
					}else if (cell != null && cell.getCellType() == cell.CELL_TYPE_NUMERIC) {//判断数字
						map.put(titleRow.getCell(j).getStringCellValue(), StringUtils.subStringBefore(String.valueOf(cell.getNumericCellValue()), "\\.", 1));
					}
						
				}
				list.add(map);
			}
		}
		return list;
	}
}
